import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';


interface UserState {
  token: string | null;
  userInfo: {
    userId?: number;
    avatar?: string;
    username?: string;
    nickname?: string;
    desc?: string;
    roles?: string[];
    perms?: string[];
  } | null;
  loading: boolean;
  error: string | null;
}

const initialState: UserState = {
  token: null,
  userInfo: null,
  loading: false,
  error: null,
};

// 登录
export const login = createAsyncThunk(
  'user/login',
  async (credentials: { username: string; password: string }) => {
    const response = await fetch('/api/user/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(credentials),
    });
    const data = await response.json();
    if (data.code !== 200) throw new Error(data.message);
    return data.data;
  }
);

// 获取用户信息
export const getUserInfo = createAsyncThunk('user/getUserInfo', async () => {
  const response = await fetch('/api/user/userInfo');
  const data = await response.json();
  if (data.code !== 200) throw new Error(data.message);
  return data.data;
});

// 登出
export const logout = createAsyncThunk('user/logout', async () => {
  const response = await fetch('/api/user/logout', {
    method: 'POST',
  });
  const data = await response.json();
  if (data.code !== 200) throw new Error(data.message);
  return null;
});

const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    clearError: (state) => {
      state.error = null;
    },
  },
  extraReducers: (builder) => {
    builder
      // Login
      .addCase(login.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(login.fulfilled, (state, action) => {
        state.loading = false;
        state.token = action.payload.token;
      })
      .addCase(login.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || '登录失败';
      })
      // Get User Info
      .addCase(getUserInfo.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(getUserInfo.fulfilled, (state, action) => {
        state.loading = false;
        state.userInfo = action.payload;
      })
      .addCase(getUserInfo.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || '获取用户信息失败';
      })
      // Logout
      .addCase(logout.fulfilled, (state) => {
        state.token = null;
        state.userInfo = null;
      });
  },
});

export const { clearError } = userSlice.actions;
export default userSlice.reducer;
